import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ResultData } from 'src/common/utils/result';
import { SysConfigEntity } from './entities/config.entity';
import { Cacheable } from 'src/common/decorators/redis.decorator';
import { RedisKeyPrefix } from '../enums/redis-key.enum';

@Injectable()
export class ConfigService {
  constructor(
    @InjectRepository(SysConfigEntity)
    private readonly sysConfigEntityRep: Repository<SysConfigEntity>,
  ) {}

  async findOne(configId: number) {
    const data = await this.sysConfigEntityRep.findOne({
      where: {
        configId: configId,
      },
    });
    return ResultData.ok(data);
  }

  /**
   * 根据配置键值异步查找一条配置信息。
   *
   * @param configKey 配置的键值，用于查询配置信息。
   * @returns 返回一个结果对象，包含查询到的配置信息。如果未查询到，则返回空结果。
   */
  // configKey：'sys.account.captchaEnabled'
  @Cacheable(RedisKeyPrefix.SYS_CONFIG_KEY, '{configKey}')
  async getConfigValue(configKey: string) {
    const data = await this.sysConfigEntityRep.findOne({
      where: { configKey: configKey },
    });
    // true
    return data?.configValue;
  }
}
